package cc.miwuya.property.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.owner.domain.Orders;
import cc.miwuya.property.client.UserClient;
import cc.miwuya.property.domain.House;
import cc.miwuya.property.domain.Meter;
import cc.miwuya.property.domain.MeterItem;
import cc.miwuya.property.service.HouseService;
import cc.miwuya.property.service.MeterItemService;
import cc.miwuya.property.service.MeterService;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 迷雾森林
 * @Date 2024-02-27 12:03
 */
@RestController
@RequestMapping("/property/meterItem")
public class MeterItemController {
    @Resource
    MeterItemService meterItemService;
    @Resource
    UserClient userClient;

    @Resource
    MeterService meterService;
    @Resource
    HouseService houseService;
    @Resource
    HttpServletRequest httpServletRequest;
    /**
     * 操作抄表记录
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody MeterItem meterItem) {
        meterItemService.saveOrUpdate(meterItem);
        return Result.success();
    }

    /**
     * 获取最近十条抄表记录
     */
    @GetMapping("/info/{meterId}")
    public Result info(@PathVariable Long meterId) {
        List<MeterItem> meterItemList = meterItemService.list(new QueryWrapper<MeterItem>().eq("meter_id", meterId).last("limit 10").orderByDesc("updated"));
        return Result.success(meterItemList);
    }

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            reader.addHeaderAlias("小区ID", "residentialId");
            reader.addHeaderAlias("计量表ID", "meterId");
            reader.addHeaderAlias("数据", "data");
            reader.addHeaderAlias("时间", "updated");
            reader.addHeaderAlias("结算状态", "status");
            List<MeterItem> meterItems = reader.readAll(MeterItem.class);
            meterItemService.saveBatch(meterItems);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    @GetMapping("/calc")
    public Result calc(Long id) {
        MeterItem success = meterItemService.getOne(new QueryWrapper<MeterItem>().eq("meter_id", id).eq("status", 1).orderByDesc("id").last("limit 1"));
        MeterItem error = meterItemService.getOne(new QueryWrapper<MeterItem>().eq("meter_id", id).eq("status", 0).orderByDesc("id").last("limit 1"));
        BigDecimal decimal = new BigDecimal(success==null?"0":success.getData()+"");
        BigDecimal decimal1 = new BigDecimal(error.getData() + "");
        Orders order = new Orders();
        order.setCreated(LocalDateTime.now());
        order.setItem("物业收费-计量表"+id+"收费");
        order.setStatus(0);
        order.setAmount(decimal1.subtract(decimal).multiply(new BigDecimal("2.4")));
        order.setTollman(getCurrent());
        order.setUserId(getOwner(id));
        userClient.addOrder(order);
        meterItemService.update(new UpdateWrapper<MeterItem>().set("status", 1).eq("meter_id",id));
        return Result.success();
    }
    public Long getCurrent(){
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        Long username = Long.parseLong(parse.getByPath("userId").toString());
        return username;
    }
    public Long getOwner(Long meterId){
        //先拿到表
        Meter meter = meterService.getById(meterId);
        House id = houseService.getOne(new QueryWrapper<House>().eq("id", meter.getHomeId()));
        System.out.println(id.getOwnerId());
        return id.getOwnerId();
    }
}
